package com.youlai.boot.modules.game.service.impl;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.youlai.boot.modules.game.converter.GameInfoConverter;
import com.youlai.boot.modules.game.mapper.GameInfoMapper;
import com.youlai.boot.modules.game.mapper.GameScreenshotMapper;
import com.youlai.boot.modules.game.mapper.GameTagMapper;
import com.youlai.boot.modules.game.mapper.GameTagRelationMapper;
import com.youlai.boot.modules.game.model.entity.GameInfo;
import com.youlai.boot.modules.game.model.entity.GameScreenshot;
import com.youlai.boot.modules.game.model.entity.GameTag;
import com.youlai.boot.modules.game.model.entity.GameTagRelation;
import com.youlai.boot.modules.game.model.form.GameInfoForm;
import com.youlai.boot.modules.game.model.form.GameScreenshotForm;
import com.youlai.boot.modules.game.model.query.GameInfoQuery;
import com.youlai.boot.modules.game.model.vo.GameInfoVO;
import com.youlai.boot.modules.game.service.GameInfoService;
import lombok.RequiredArgsConstructor;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

/**
 * 游戏信息服务实现类
 *
 * @author 有来技术团队
 */
@Service
@RequiredArgsConstructor
public class GameInfoServiceImpl extends ServiceImpl<GameInfoMapper, GameInfo> implements GameInfoService {

    private final GameInfoMapper gameInfoMapper;
    private final GameScreenshotMapper gameScreenshotMapper;
    private final GameTagMapper gameTagMapper;
    private final GameTagRelationMapper gameTagRelationMapper;
    private final GameInfoConverter gameInfoConverter;

    @Override
    public Page<GameInfoVO> getGamePage(GameInfoQuery queryParams) {
        Page<GameInfo> page = new Page<>(queryParams.getPageNum(), queryParams.getPageSize());
        return gameInfoMapper.getGamePage(page, queryParams);
    }

    @Override
    public GameInfoVO getGameDetail(Long id) {
        GameInfoVO gameInfoVO = gameInfoMapper.getGameById(id);
        if (gameInfoVO != null) {
            // 获取游戏截图
            List<GameScreenshot> screenshots = gameScreenshotMapper.getScreenshotsByGameId(id);
            gameInfoVO.setScreenshots(screenshots);
            
            // 获取游戏标签
            List<GameTag> tags = gameTagMapper.getTagsByGameId(id);
            gameInfoVO.setTags(tags);
        }
        return gameInfoVO;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public Long addGame(GameInfoForm formData) {
        // 转换为实体并保存
        GameInfo gameInfo = gameInfoConverter.form2Entity(formData);
        save(gameInfo);
        
        Long gameId = gameInfo.getId();
        
        // 保存游戏标签关系
        saveGameTags(gameId, formData.getTagIds());
        
        // 保存游戏截图
        saveGameScreenshots(gameId, formData.getScreenshots());
        
        return gameId;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean updateGame(Long id, GameInfoForm formData) {
        // 设置ID并更新
        formData.setId(id);
        GameInfo gameInfo = gameInfoConverter.form2Entity(formData);
        boolean result = updateById(gameInfo);
        
        if (result) {
            // 更新游戏标签关系
            gameTagRelationMapper.deleteByGameId(id);
            saveGameTags(id, formData.getTagIds());
            
            // 更新游戏截图
            gameScreenshotMapper.deleteByGameId(id);
            saveGameScreenshots(id, formData.getScreenshots());
        }
        
        return result;
    }

    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean deleteGames(List<Long> ids) {
        for (Long id : ids) {
            // 删除游戏标签关系
            gameTagRelationMapper.deleteByGameId(id);
            
            // 删除游戏截图
            gameScreenshotMapper.deleteByGameId(id);
        }
        
        // 删除游戏信息
        return removeByIds(ids);
    }

    @Override
    public List<GameInfoVO> getFeaturedGames(Integer limit) {
        return gameInfoMapper.getFeaturedGames(limit);
    }

    @Override
    public List<GameInfoVO> getHotGames(Integer limit) {
        return gameInfoMapper.getHotGames(limit);
    }

    @Override
    public List<GameInfoVO> getNewGames(Integer limit) {
        return gameInfoMapper.getNewGames(limit);
    }

    @Override
    public List<GameInfoVO> getGamesByCategory(Long categoryId, Integer limit) {
        return gameInfoMapper.getGamesByCategory(categoryId, limit);
    }

    @Override
    public boolean incrementDownloadCount(Long id) {
        return gameInfoMapper.incrementDownloadCount(id) > 0;
    }

    @Override
    public boolean updateRating(Long id, Double rating) {
        return gameInfoMapper.updateRating(id, rating) > 0;
    }

    /**
     * 保存游戏标签关系
     *
     * @param gameId 游戏ID
     * @param tagIds 标签ID列表
     */
    private void saveGameTags(Long gameId, List<Long> tagIds) {
        if (tagIds != null && !tagIds.isEmpty()) {
            gameTagRelationMapper.batchSave(gameId, tagIds);
        }
    }

    /**
     * 保存游戏截图
     *
     * @param gameId     游戏ID
     * @param screenshots 截图列表
     */
    private void saveGameScreenshots(Long gameId, List<GameScreenshotForm> screenshots) {
        if (screenshots != null && !screenshots.isEmpty()) {
            List<GameScreenshot> screenshotEntities = screenshots.stream().map(screenshot -> {
                GameScreenshot entity = new GameScreenshot();
                entity.setGameId(gameId);
                entity.setImageUrl(screenshot.getImageUrl());
                entity.setDescription(screenshot.getDescription());
                entity.setSort(screenshot.getSort());
                return entity;
            }).collect(Collectors.toList());
            
            for (GameScreenshot screenshot : screenshotEntities) {
                gameScreenshotMapper.insert(screenshot);
            }
        }
    }
} 